package com.htl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.htl.entity.Admin;
import com.htl.exception.ShopException;
import com.htl.form.AdminForm;
import com.htl.result.ResponseEnum;
import com.htl.service.AdminService;
import com.htl.util.JwtUtil;
import com.htl.util.ResultVOUtil;
import com.htl.vo.AdminVO;
import com.htl.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 韩天乐
 * @since 2021-11-14
 */

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/login")
    public ResultVO login(@Valid AdminForm adminForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new ShopException(ResponseEnum.USER_INFO_NULL.getMsg());
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminForm.getUsername());
        queryWrapper.eq("password", adminForm.getPassword());
        Admin one = this.adminService.getOne(queryWrapper);
        if(one == null) {
            throw new ShopException(ResponseEnum.LOGIN_ERROR.getMsg());
        }
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(one, adminVO);
        adminVO.setToken(JwtUtil.createToken(one.getAdminId(), one.getUsername()));
        return ResultVOUtil.success(adminVO);
    }


    @GetMapping("/checkToken")
    public ResultVO checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean b = JwtUtil.checkToken(token);
        if(b) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(null);
    }

}

